﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Web;

namespace InventoryManagementServer
{
    public abstract class HttpHandlerBase : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            try
            {
                var userXml = Uri.UnescapeDataString(context.Request.Headers["User"]);
                var user = XmlSerializer.Deserialize<User>(userXml);

                if (!user.Validate())
                {
                    throw new UnauthorizedAccessException();
                }

                string requestBody = string.Empty;
                using (var stream = new StreamReader(context.Request.InputStream))
                {
                    requestBody = stream.ReadToEnd();
                }
                
                string responseBody = string.Empty;
                ProcessRequest(user, context.Request, requestBody, context.Response, ref responseBody);
                
                context.Response.AddHeader("Result", "OK");

                context.Response.Write(responseBody);
            }
            catch
            {
                context.Response.AddHeader("Result", "ERROR");
            }
        }

        public abstract void ProcessRequest(User user, HttpRequest request, string requestBody, HttpResponse response, ref string responseBody);
    }
}